/**
* 收藏
*/
'use strict'

import Api from "../common/Api"
import Util from "../common/Util"
import TopTabBar from "../common/TopTabBar"

import Login from "./login"
import BlogDetail from "./blog_detail"
import NewsDetail from "../news/news_detail"
import SoftwareDetail from "./software_detail"

var React = require('react-native');

var {
  ScrollView,
  View,
  StyleSheet,
  SegmentedControlIOS,
  AsyncStorage,
  AlertIOS,
  TouchableOpacity,
  ListView,
  Text,
}=React;

export default class Favorite extends React.Component{
  constructor(props){
    super(props)
    this._loadContent=this._loadContent.bind(this);

    this.state={
      types:['软件','话题','博客','资讯','代码'],
      selectedValue:'软件',
      uid:'',
      key:'',
      type:1,
      dataList:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows([]),
      show:false,
    }
  }

  componentDidMount(){
    this._loadContent('软件');
  }

  _loadContent(tab){
    var that = this;
    this.setState({
      dataList:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows([]),
      show:false,
    })
    this.state.types.forEach((data,index)=>{
      if(data===tab){
        that.setState({
          type:index+1,
          selectedValue:data
        })
      }
    })

    AsyncStorage.getItem('uid')
      .then((value)=>{
        if(value!=null){
          that.setState({
            uid:value
          })
          AsyncStorage.getItem('key')
            .then((key)=>{
              that.setState({
                key:key
              })
              var url=Api.favorite_list;
              var params={
                uid:that.state.uid,
                type:that.state.type,
                key:that.state.key
              }
              console.log('GET favorite url:'+url+';;params='+JSON.stringify(params));
              Util.post(url,params,(data)=>{
                console.log(JSON.stringify(data));

                that.setState({
                  show:true,
                })
                if(parseInt(data.oschina.pagesize)>0){
                  console.log(JSON.stringify(data.oschina.favorites.favorite))
                  var objs=data.oschina.favorites.favorite;
                  var dataList=[];
                  if(!Array.isArray(objs)){
                    dataList.push(objs);
                  }else{
                    dataList=objs;
                  }
                  that.setState({
                    dataList:new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(dataList),
                  })
                }

              })
            })
            .catch((err)=>{
              AlertIOS.alert('收藏',err);
            })
            .done();
        }else{
          that.props.navigator.push({
            component:<Login/>,
            title:'登录'
          })
        }
      })
      .catch((err)=>{
        AlertIOS.alert('收藏',err);
      })
      .done();

  }

  _loadDetailPage(objid){
    const type=this.state.type;
    if(type===3){
      this.props.navigator.push({
        component:<BlogDetail objid={objid}/>,
        title:'博客详情'
      })
    }else if(type===4){
      this.props.navigator.push({
        component:<NewsDetail id={objid}/>,
        title:'资讯详情'
      })
    }else if(type===1){
      this.props.navigator.push({
        component:<SoftwareDetail id={objid}/>,
        title:'软件详情'
      })
    }

  }

  render(){
    return (
      <View>
        {/*
          <SegmentedControlIOS
            tintColor='#4ead7d'
            style={styles.news_tag}
            selectedIndex={0}
            values={this.state.types}
            onValueChange={(val)=>{
              this.setState({
                selectedValue:val
              });
              this._loadContent(val);
            }}
            />*/}
          <TopTabBar
            tabs={this.state.types}
            initTab={0}
            onValueChange={(val,i)=>{
              this.setState({
                selectedValue:val
              });
              this._loadContent(val);
            }}
            />
        <ScrollView style={styles.content}>
          {
            this.state.show?
            <ListView
              dataSource={this.state.dataList}
              renderRow={(row)=>
                <FavoriteItem row={row} onPress={this._loadDetailPage.bind(this,row.objid)} {...this.props}/>
              }
              />
            :Util.loading
          }
        </ScrollView>
      </View>

    );
  }
}

class FavoriteItem extends React.Component{
  constructor(props){
    super(props)
  }

  render(){
    const {row}=this.props;

    return (
      <TouchableOpacity  {...this.props}>
        <View style={styles.item}>
          <Text style={styles.title}>{row.title}</Text>
        </View>
      </TouchableOpacity>

    );
  }
}


var styles = StyleSheet.create({
  content:{

  },
  news_tag:{
    backgroundColor:'#f0e9eb',
    marginTop:-5,
  },
  item:{
    minHeight:40,
    borderBottomWidth:Util.pixel,
    borderColor:'#ccc',
    paddingBottom:10,
    paddingTop:10,
    justifyContent:'center'
  },
  title:{
    paddingLeft:10,
  }
})
